<template>
  <div class="play">
    <!-- 留声机 - 容器 -->
    <div class="song_bgi">
      <div class="song-bg" :style="`background-image: url(${
        songInfo && songInfo.al && songInfo.al.picUrl
      }?imageView&thumbnail=360y360&quality=75&tostatic=0);`"></div>

      <i class="el-icon-back" @click="$refs.audio.pause();$router.go(-1);"></i>

      <div class="song-wrapper">
        <!-- 留声机本身(靠css动画做旋转) -->
        <div class="song-turn ani"
          :style="`animation-play-state:${playState ? 'running' : 'paused'}`">
          <div class="song-img">
            <!-- &&写法是为了防止报错, 有字段再继续往下访问属性 -->
            <img style="width: 100%" :src="`${
              songInfo && songInfo.al && songInfo.al.picUrl
            }?imageView&thumbnail=360y360&quality=75&tostatic=0`" alt="" />
          </div>
        </div>
        <!-- 播放按钮 -->
        <div class="start-box" @click="audioStart">
          <span class="song-start" v-show="!playState"></span>
        </div>
        <!-- 播放歌词容器 -->
        <div class="song-msg">
          <!-- 歌曲名 -->
          <h2 class="m-song-h2">
            <h2>{{ songInfo.name }}</h2>
          </h2>
          <h2 class="m-song-h2">
            <div>歌手：
              <span v-if="artists" v-for="(val,ind) in artists" class="artClass"
                :key="ind" @click="singer(val.id)">
                {{val.name}}
              </span>
            </div>
            <div style="margin-top:10px">专辑：
              <span class="artClass"
                @click='album(songInfo)'>{{songInfo&&songInfo.al&& songInfo.al.name}}</span>
            </div>
          </h2>
          <!-- 歌词部分-随着时间切换展示一句歌词 -->

        </div>
        <!-- 留声机 - 唱臂 -->
        <div class="needle" :style="`transform: rotate(${needleDeg});`"></div>

      </div>
      <div class="lrcContent" ref='lrcContent'>
        <div class="curLyricCls">
          <div :class="{curLyricRow:lastLyOffset == ind}" class="Showlrc"
            v-for="(val,ind) in ShowLyricList" :key="ind">
            <!-- 歌词 -->
            {{val}}
          </div>

        </div>
      </div>
    </div>

    <audio ref="audio" preload="true" controls style="width:0px"
      :src="`https://music.163.com/song/media/outer/url?id=${id}.mp3`"></audio>

    <div class="musicControls">
      <div @click="audioStart" class="leftIcon">
        <i v-show="!playState" class="el-icon-video-play"
          style="position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);z-index:1;font-size:50px;color:white"></i>
        <el-image style="width: 100%; height: 100%"
          v-if="songInfo && songInfo.al &&songInfo.al.picUrl!== undefined"
          :src="`${songInfo && songInfo.al && songInfo.al.picUrl}`"
          fit="cover"></el-image>
      </div>
      <div class="time">
        <span>{{timeLfet[0]+':'+timeLfet[1]}}</span>/
        <span>{{timeRight[0]+':'+timeRight[1]}}</span>
      </div>

      <el-slider class="long_Strip" v-model="slider" :show-tooltip="true"
        :format-tooltip='()=>timeLfet[0]+":"+timeLfet[1]' @change="sliderChange"
        @input="sliderChange2"
        @mousedown.native='$refs.audio.pause(); playState =false'
        @mouseup.native="$refs.audio.play(); playState = true"></el-slider>
      <div class="btn">
        <el-button @click="like(songInfo)">收藏</el-button>
        <el-button type="danger" @click="download">下载</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { MusicDetails, GetLyric } from '../../api/Play.js'
import { timeChange } from '../../utils/tools'
import download from "../../../node_modules/downloadjs/download.js"
export default {
  name: '',
  data () {
    return {
      playState: false, // 音乐播放状态(true暂停, false播放)
      id: JSON.parse(this.$route.query.val).id, // 上一页传过来的音乐id
      songInfo: {}, // 歌曲信息
      lyric: {}, // 歌词枚举对象(需要在js拿到歌词写代码处理后, 按照格式保存到这个对象)
      curLyric: "", // 当前显示哪句歌词
      lastLy: "", // 记录当前播放歌词
      artists: [],
      // 作者
      lastLyOffset: 0,
      // 歌词位置
      lyricList: [],
      // 记录有标记的显示歌词数组
      ShowLyricList: [],
      // 真正显示的歌词列表
      translateList: [],
      // 翻译歌词列表
      scrollFlag: true,
      timeLfet: ['00', '00'],
      // 正在播放的时间
      timeRight: '',
      // 歌曲总时间
      slider: 0,
      flag: false,
      scrollFlag: true
      // 是否滚动歌词
    };
  },
  async created () {
    let res = await MusicDetails({ ids: JSON.parse(this.$route.query.val).id })
    // 接收通过路由传参过来的参数,并转换为正常参数
    this.songInfo = res.data.songs[0]
    // console.log(this.songInfo.ar);
    this.artists = this.songInfo.ar
    this.timeRight = timeChange(this.songInfo.dt)
    let lyrContent = await GetLyric({ id: JSON.parse(this.$route.query.val).id })
    // 获取歌词
    if (lyrContent.data.qfy && lyrContent.data.sfy && lyrContent.data.sgc) {
      // 若歌词不是正常格式
      this.ShowLyricList = lyrContent.data.lrc.lyric.split('\n')
      this.ShowLyricList.unshift('/*该字幕无法滚动*/')
      this.scrollFlag = false
      return
    }
    this.lyric = this.ChangeLyric(lyrContent.data.lrc.lyric)
    // 两个歌词 第一个是没有标识符的歌词，第二个是带标识符的歌词
    this.curLyric = this.lyric[1][0]
    // 当前显示第一个歌词
    this.lyricList = Object.values(this.lyric[1])
    // 用于与歌曲同步滚动的歌词
    this.ShowLyricList = Object.values(this.lyric[0])
    // 真正显示的歌词
    if (lyrContent.data.tlyric && (lyrContent.data.tlyric.lyric.trim().length !== 0)) {
      // 若存在翻译
      this.translateList = Object.values(this.ChangeLyric(lyrContent.data.tlyric.lyric)[0])
      // 用于存储新数组
      let writer = []
      // 作曲和翻译
      if (this.ShowLyricList[0].indexOf('作词') !== -1 && this.ShowLyricList[1].indexOf('作曲') !== -1) {
        // 歌词若有作词和翻译则不给这两个元素添加翻译
        writer.push(this.ShowLyricList[0])
        writer.push(this.ShowLyricList[1])
        this.lyricList.splice(0, 2)
        this.ShowLyricList.splice(0, 2)
      }
      let proList = []
      let proList2 = []
      this.translateList.forEach((val, ind) => {
        proList2.push(this.lyricList[ind])
        proList2.push(val)
        proList.push(this.ShowLyricList[ind])
        proList.push(val)
      })
      proList.unshift(...writer)
      proList2.unshift(...writer)
      this.lyricList = proList2
      this.ShowLyricList = proList
    }
  },
  mounted () {
    this.showLyric()

  },
  methods: {
    audioStart () {
      // 播放按钮 - 点击事件
      if (!this.playState) {
        // 如果状态为false
        this.$refs.audio.play();
        // 调用audio标签的内置方法play可以继续播放声音
      } else {
        this.$refs.audio.pause(); // 暂停audio的播放
      }
      this.playState = !this.playState; // 点击设置对立状态
    },
    ChangeLyric (lyricStr, translate = null) {
      // 可以看network观察歌词数据是一个大字符串, 进行拆分.
      let reg = /\[.+?\]/g; //
      // 正则
      let timeArr = lyricStr.match(reg); // 匹配所有[]字符串以及里面的一切内容, 返回数组
      // console.log(timeArr); // ["[00:00.000]", "[00:01.000]", ......]
      let contentArr = lyricStr.split(/\[.+?\]/).slice(1); // 按照[]拆分歌词字符串, 返回一个数组(下标为0位置元素不要,后面的留下所以截取)
      // console.log(contentArr);
      let lyricObj = {}; // 保存歌词的对象, key是秒, value是显示的歌词
      let lyricObj2 = {}
      timeArr.forEach((item, index) => {
        // 拆分[00:00.000]这个格式字符串, 把分钟数字取出, 转换成秒
        let ms = item.split(":")[0].split("")[2] * 60;
        // 拆分[00:00.000]这个格式字符串, 把十位的秒拿出来, 如果是0, 去拿下一位数字, 否则直接用2位的值
        let ss =
          item.split(":")[1].split(".")[0].split("")[0] === "0"
            ? item.split(":")[1].split(".")[0].split("")[1]
            : item.split(":")[1].split(".")[0];
        // 秒数作为key, 对应歌词作为value
        lyricObj[ms + Number(ss)] = contentArr[index]
        lyricObj2[ms + Number(ss)] = contentArr[index] + '-&-&-' + index;
      });
      return [lyricObj, lyricObj2];
    },
    showLyric () {
      this.$refs.audio.addEventListener("timeupdate", (e) => {
        let curTime = Math.floor(this.$refs.audio.currentTime);
        // 播放时间
        this.slider = ((this.$refs.audio.currentTime * 1000) / this.songInfo.dt) * 100
        // 正在进行时间/总时间  *100 = 歌曲百分比
        if (curTime == Math.floor(this.songInfo.dt / 1000)) {
          this.$refs.audio.currentTime = 0
          return this.audioStart()
        }
        if (!this.scrollFlag) return

        let num = Object.keys(this.lyric[1]).filter((val2, ind) => {
          // val2是歌词的对应时间，val是点击的对应时间
          // 点击的时间大于歌词对应的时间
          return val2 < this.$refs.audio.currentTime
        })
        this.curLyric = this.lyric[1][num[num.length - 1]]
        // 当前显示歌词 = 歌词列表里指定歌词时间


        this.timeLfet = timeChange(curTime * 1000)
        // 播放完毕的时间

        this.lyricList.find((val, ind) => {
          // 把加完索引号的歌词列表进行检索
          if (val == this.curLyric) {
            // 当找到显示的歌词时，就让下标赋值给offset
            return this.lastLyOffset = ind
          }
        })
        this.$refs.lrcContent.scrollTo(0, 23.5 * this.lastLyOffset)
        if (this.lyric[1][curTime]) {
          // 若当前显示歌词存在
          this.curLyric = this.lyric[1][curTime];
          // 显示当前歌词
          this.lastLy = this.curLyric;
          // 当前播放的歌词 = 当前显示的歌词
        } else {
          this.curLyric = this.lastLy;
          // 当歌词不存在时，让当前显示的歌词 = 记录的歌词
          // 为了不留空白
        }
      });
    },
    sliderChange (val) {
      // 点击滑动块，松开鼠标后触发一次
      // this.$refs.audio.currentTime = ((this.songInfo.dt / 1000) * (val / 100))
      // 总时间(毫秒数)/1000=秒 ；val数字/100=百分比 ；总的秒数*百分比 = 实时秒数
      this.$refs.audio.currentTime = (this.songInfo.dt * val) / 100000
    },
    sliderChange2 (val) {
      // 歌曲播放就一直不间断的触发该事件
      if (val == 0) return
      this.timeLfet = timeChange((this.songInfo.dt * val) / 100)
    },
    like (val) {
      let local = JSON.parse(localStorage.getItem('UserInfoList')).music
      if (Boolean(local.find((val2) => val2.id == val.id))) return this.ErrorAlert('歌曲已收藏过')
      // this.$store.dispatch('CMusic', { })
      this.$store.dispatch('Change', ['music', { id: val.id, title: val.name, name: val.ar, dt: val.dt }])
      // 添加数据到本地
      this.ErrorAlert('收藏成功', 'success')
    },
    download () {
      download(JSON.parse(this.$route.query.url))
    },
    singer (id) {
      // 歌手
      this.$router.push({ name: 'singer', query: { id: id } })
    },
    album (val) {
      // 专辑
      this.$router.push({ name: 'album', query: { id: val.al.id } })
    },
    ErrorAlert (mes, ty = 'error') {
      // 错误提示
      return this.$message({
        message: mes,
        duration: 700,
        type: ty
      });
    }
  },
  components: {},

  props: {
  },

  watch: {},

  computed: {
    needleDeg () {
      // 留声机-唱臂的位置属性
      return this.playState ? "-7deg" : "-38deg";
    }
  },

}

</script>
<style scoped >
.header {
  height: 50px;
  color: red;
}
.play {
  position: absolute;
  padding-top: 10px;
  width: 100%;
  top: 60px;
  bottom: 0px;
}
.song-bg {
  background-color: #161824;
  background-position: 50%;
  background-repeat: no-repeat;
  transform-origin: center;
  position: absolute;
  z-index: 0;
  background-size: cover;
  width: 100%;
  height: 100%;
  overflow: hidden;
  filter: blur(25px);
}

.song-bg::before {
  content: " ";
  background: rgba(0, 0, 0, 0.5);
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}
/*纯白色的图片做背景, 歌词白色看不到了, 在背景前加入一个黑色半透明蒙层解决 */

.song_bgi {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-size: auto 100%;
  transform-origin: center;
}
.el-icon-back {
  /* 返回按钮 */
  position: absolute;
  z-index: 0;
  top: 4%;
  left: 4%;
  color: white;
  cursor: pointer;
  font-size: 40px;
}
.song-wrapper {
  position: absolute;
  width: 247px;
  height: 247px;
  left: 20%;
  top: 150px;
  transform: translateX(-50%);
  z-index: 1;
}
.song-turn {
  width: 100%;
  height: 100%;
  background: url("../../assets/Play_images/bg.png") no-repeat;
  background-size: 100%;
}
.start-box {
  position: absolute;
  width: 156px;
  height: 156px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  justify-content: center;
  align-items: center;
}
.song-start {
  width: 56px;
  height: 56px;
  background: url("../../assets/Play_images/start.png");
  background-size: 100%;
}
.needle {
  position: absolute;
  transform-origin: left top;
  background: url("../../assets/Play_images/needle-ab.png") no-repeat;
  background-size: contain;
  width: 73px;
  height: 118px;
  top: -40px;
  left: 112px;
  transition: all 0.6s;
}
.song-img {
  width: 154px;
  height: 154px;
  position: absolute;
  left: 50%;
  top: 50%;
  overflow: hidden;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}
.m-song-h2 {
  margin-top: 20px;
  text-align: center;
  font-size: 18px;
  color: #fefefe;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.lrcContent {
  position: absolute;
  top: 12%;
  left: 40%;
  width: 40%;
  height: 70%;
  /* border: 1px solid white; */
  z-index: 0;
  color: #000;
  overflow-y: scroll;
}
.lrcContent::-webkit-scrollbar {
  /* 歌词滚动条背景 */
  -webkit-appearance: none;
  height: 20px;
  /* background-color: red; */
  /* border: 1px solid #000; */
}
.lrcContent::-webkit-scrollbar:vertical {
  width: 15px;
}
.lrcContent::-webkit-scrollbar-thumb {
  /* 歌词滚动条内轴 */
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.5);
}
.curLyricCls {
  margin-top: 45%;
  margin-bottom: 55%;
}
.curLyricRow {
  color: red !important;
}
.ani {
  animation: turn 5s linear infinite;
}
@keyframes turn {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}
.musicControls {
  width: 100%;
  position: fixed;
  bottom: 5%;
}
.long_Strip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, 5%);
  width: 60%;
  border-radius: 10px;
}

.leftIcon {
  position: relative;
  left: 5%;
  bottom: 0px;
  transform: translateY(10%);
  width: 100px;
  height: 100px;
  border: 1px solid #000;
}
.time {
  position: absolute;
  top: 28%;
  left: 71%;
  z-index: 2;
  color: white;
}
.btn {
  position: absolute;
  right: 5%;
  top: 50%;
}
.Showlrc {
  color: white;
  font-size: 17px;
  line-height: 23px;
  height: 23px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.artClass {
  cursor: pointer;
}
.artClass:hover {
  color: red;
}
</style>